package com.jackykeke.kdatabasedemo.db

import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log

object DatabaseUtils {

    val TYPE_BLOB = "blob"

    val TYPE_TEXT = "text"

    val TYPE_NUMERIC = "numeric"


    @Throws(DatabaseException::class)
    fun insert(sqLiteOpenHelper: SQLiteOpenHelper, vararg insertParams: InsertParams): Boolean {
        var isSuccess = false


        insertParams?.let {
            if (it.isNotEmpty()) {
                var db: SQLiteDatabase? = null

                try {
                    db = sqLiteOpenHelper.writableDatabase
                    db.beginTransaction()

                    it.forEach { param ->
                        db.insert(param.tableName, null, param.contentValues)
                    }
                    isSuccess = true

                } catch (e: Exception) {
                    throw  DatabaseException(e)
                } finally {
                    if (null != db) {

                        try {
                            db.endTransaction()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

        }

        return isSuccess
    }


    @Throws(DatabaseException::class)
    fun insert(
        sqLiteOpenHelper: SQLiteOpenHelper,
        tableName: String?,
        initialValues: ContentValues?
    ): Long {
        var rowId: Long = 0
        rowId = try {
            val db = sqLiteOpenHelper.writableDatabase
            db.insert(tableName, null, initialValues)
        } catch (e: java.lang.Exception) {
            throw DatabaseException(e)
        }
        return rowId
    }

    fun delete(sqLiteOpenHelper: SQLiteOpenHelper, list: List<DeleteParams>?): Boolean {

        var isSuccess = false

        list?.isNotEmpty().let {
            var db: SQLiteDatabase? = null


            try {
                db = sqLiteOpenHelper.writableDatabase
                db.beginTransaction()

                list?.forEach { deleParam ->
                    db.delete(deleParam.tableName, deleParam.selection, deleParam.whereArgs)
                }
                db.setTransactionSuccessful()
                isSuccess = true
            } catch (e: Exception) {
                throw DatabaseException(e)
            } finally {
                if (null != db) {
                    try {
                        db.endTransaction()
                    } catch (e: java.lang.Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }

        return isSuccess
    }

    fun update(sqLiteOpenHelper: SQLiteOpenHelper, list: List<UpdateParams>?): Boolean {
        var isSuccess = false
        list?.let {
            if (it.isNotEmpty()) {
                var db: SQLiteDatabase? = null
                try {
                    db = sqLiteOpenHelper.writableDatabase
                    db.beginTransaction()
                    it.forEach { updateParam ->
                        db.update(
                            updateParam.tableName, updateParam.contentValues, updateParam.selection,
                            updateParam.whereArgs
                        )
                    }

                    db.setTransactionSuccessful()
                    isSuccess = true

                } catch (e: Exception) {
                    throw  DatabaseException(e)
                } finally {
                    if (null != db) {
                        try {
                            db.endTransaction()
                        } catch (e: java.lang.Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }
        return isSuccess
    }


    /**
     * 用于单表查询
     */

    /**
     * Query the given table, returning a {@link Cursor} over the result set.
     *
     * @param table The table name to compile the query against.
     * @param projection  要返回的列的列表。传递null将返回所有列，这是不鼓励的，以防止从不使用的存储读取数据。
     * @param selection  一个声明要返回哪些行的过滤器，格式为SQL WHERE子句(不包括WHERE本身)。传递null将返回给定表的所有行。
     * @param selectionArgs  您可以在选择中包含?s，它将被selectionArgs中的值替换，以便它们出现在选择中。这些值将被绑定为字符串。
     * @param groupBy  声明如何分组行的过滤器，格式化为SQL group BY子句(不包括group BY本身)。传递null将导致行不能分组。
     *
     * @param having   如果正在使用行分组，筛选器声明要在游标中包含哪些行组，格式化为SQL HAVING子句(不包括HAVING本身)。
     *                  传递null将导致包含所有行组，并且在不使用行分组时是必需的。
     *
     * @param orderBy  如何排序的行，格式化为SQL order BY子句(不包括命令本身)。传递null将使用默认排序顺序，可能是无序的。
     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
     * {@link Cursor}s are not synchronized, see the documentation for more details.
     * @see Cursor
     */

    open fun query(
        sqLiteOpenHelper: SQLiteOpenHelper,
        tableName: String,
        projection: Array<String>?,
        selection: String?,
        selectionArgs: Array<String>?,
        groupBy: String?,
        having: String?,
        sortOrder: String?
    ): Cursor? {

        var result: Cursor? = null

        try {
            Log.d("DatabaseUtils", "query start")

            val db = sqLiteOpenHelper.readableDatabase
            result = db.query(
                tableName,
                projection,
                selection,
                selectionArgs,
                groupBy,
                having,
                sortOrder
            )
            Log.d("DatabaseUtils", "query result==null?:${result == null}")
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return result
    }


}